/** 
 * projectName:  
 * fileName:  
 * packageName:  
 * date: 
 * copyright(c) 2017-2020 xxx公司
 */
package cn.wxgzh.web;


import cn.itcast.pojo.gzh;
import cn.itcast.pojo.gzhExample;
import cn.itcast.util.AuthUtil;
import cn.itcast.util.CookieUtil;
import cn.itcast.util.OutputStringController;
import cn.wxgzh.service.WxgzhService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import oracle.jrockit.jfr.VMJFR;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static cn.itcast.util.HttpClientUtil.doPost;
import static cn.itcast.util.HttpClientUtil.sendPost;

/**
 * @title: homeController.java
 * @package com.job.controller
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2020年3月18日 下午8:57:15
 * @version: V1.0
*/
@Slf4j
@RestController
@RequestMapping(value="/wxshop/wxgzh",produces="text/html;charset=UTF-8")
public class WxgzhController {

	@Resource
	WxgzhService WxgzhService;
	@Resource
    OutputStringController osc;

	@Resource
	cn.itcast.mapper.gzhMapper gzhMapper;

	@Resource
    CookieUtil cookieUtil;

	/**
	 * @title:
	 * @description:
	 * @param:
	 * @throws:
	 */
	@ResponseBody
	@GetMapping(value="/open", produces = "application/json;charset=UTF-8")
	public BigInteger login(HttpServletRequest request) {

		String signature=request.getParameter("signature");
		String timestamp=request.getParameter("timestamp");
		String nonce=request.getParameter("nonce");
		BigInteger echostr= BigInteger.valueOf(Long.parseLong(request.getParameter("echostr")));
		String token="Z5GnCVzxfx889yfAKrOi";
		String jiami="";

		log.debug("验证token");
		//排序
		String[] arr = {token, timestamp, nonce};
		Arrays.sort(arr);

		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}

		//sha1Hex 加密
		MessageDigest md = null;
		String temp = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(content.toString().getBytes());
			temp = byteToStr(digest);
			log.info("加密后的token:"+temp);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		if ((temp.toLowerCase()).equals(signature)){
			return echostr;
		}
		return null;
	}

	private static String byteToStr(byte[] byteArray){
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	private static String byteToHexStr(byte mByte){
		char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4)& 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];
		String s = new String(tempArr);
		return s;
	}


	@ResponseBody
	@GetMapping(value="/getOpenId")
	public String getOpenId(HttpServletRequest request) {
		/**
		 * 获取code
		 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8153b9b18ebfa8eb&redirect_uri=https%3a%2f%2fwww.dhnep.cn%2fwxshop%2fwxgzh%2fgetOpenId&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
		 */
		log.debug("获取用户OpenId开始");

		String code=request.getParameter("code");
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APP_ID
				+ "&secret="+ AuthUtil.APP_SECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject jsonObject;
		try {
			jsonObject = AuthUtil.doGetJson(url);
			String openid=jsonObject.getString("openid");
			String token=jsonObject.getString("access_token");
			/**
			 * 拉取用户信息
			 */
			String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+token
					+ "&openid="+openid
					+ "&lang=zh_CN";
			JSONObject userInfo=AuthUtil.doGetJson(infoUrl);//这里的userInfo已经是用户的信息了

			//将用户公众号openId存入数据库
			gzh gzh = new gzh();
			gzh.setOpenAppid(openid);
			gzh.setAccessToken((String) userInfo.get("nickname"));
			gzhExample gEx = new gzhExample();
			gzhExample.Criteria criteria = gEx.createCriteria();
			criteria.andOpenAppidEqualTo(openid);
			if(gzhMapper.selectByExample(gEx).isEmpty()){
				gzhMapper.insertSelective(gzh);
			}


			log.debug(userInfo.toString());
			log.debug("获取用户信息");
			log.debug("openId:"+openid);

			//创建开放平台
			//createGZPT(token);

			//返回结果
			String results = "";
			if(userInfo!=null){
				results = osc.resultSuccess("yes",userInfo);
				log.debug("获取用户openId");
			}else{
				results = osc.failure("no");
				log.debug("获取用户OpenId失败");
			}

			return results;
			//使用微信用户信息直接登录，无需注册和绑定

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}


	public String createGZPT(String token){
		//String token = gzhMapper.selectByPrimaryKey(1).getAccessToken();
		//创建开放平台账号
		String createUlr = "https://api.weixin.qq.com/cgi-bin/open/create?access_token="+token;
		//将公众号和小程序绑定到开放平台
		String bindUlr = "https://api.weixin.qq.com/cgi-bin/open/bind?access_token="+token;
		Map<String,String> param = new HashMap<>();
		param.put("appid","wx8153b9b18ebfa8eb");
		String result = doPost(createUlr, param);
		log.debug("创建开放平台返回数据:"+result);
//		String xcxresult = sendPost(bindUlr, "appid=wx1cf12dee9dbfe13c");
//		log.debug("小程序骑手端绑定返回数据:"+xcxresult);
//		String xceresult = sendPost(bindUlr, "appid=wx51d55df222d9901e");
//		log.debug("小程序用户端绑定返回数据:"+xceresult);
		log.debug(result);
		com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
		log.debug(object.getString("open_appid"));
		gzh gzh = new gzh();
		gzh.setId(1);
		gzh.setOpenAppid(object.getString("open_appid"));
		gzhMapper.updateByPrimaryKeySelective(gzh);

		return "";
	}

	public String getGzhToken() {

		log.debug("获取公众号Token开始");

		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8153b9b18ebfa8eb&secret=c8bf9f0c564f7f44a297054995e6eada";
		JSONObject jsonObject;
		try {

			jsonObject = AuthUtil.doGetJson(url);
			if(!jsonObject.has("errcode")){
				String access_token=jsonObject.getString("access_token");
				Integer expires_in= jsonObject.getInt("expires_in");
				log.debug(access_token);
				log.debug(expires_in.toString());
				gzh gzh = new gzh();
				gzh.setId(1);
				gzh.setAccessToken(access_token);
				gzh.setExpiresIn(expires_in);
				int i = gzhMapper.updateByPrimaryKeySelective(gzh);
				if(i==1){
					return access_token;
				}else {
					return "";
				}
			}



		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}


	public String getToken() {

		log.debug("获取骑手小程序Token开始");

		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx1cf12dee9dbfe13c&secret=3cc77b318a90be3529af5b300ba46224";
		JSONObject jsonObject;
		try {

			jsonObject = AuthUtil.doGetJson(url);
			if(!jsonObject.has("errcode")){
				String access_token=jsonObject.getString("access_token");
				Integer expires_in= jsonObject.getInt("expires_in");
				log.debug(access_token);
				log.debug(expires_in.toString());
				gzh gzh = new gzh();
				gzh.setId(2);
				gzh.setAccessToken(access_token);
				gzh.setExpiresIn(expires_in);
				int i = gzhMapper.updateByPrimaryKeySelective(gzh);
				if(i==1){
					return access_token;
				}else {
					return "";
				}
			}



		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	public String getUserToken() {

		log.debug("获取用户小程序Token开始");

		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx51d55df222d9901e&secret=5f71b93e3a56d190c10c8612fc1eb5fb";
		JSONObject jsonObject;
		try {

			jsonObject = AuthUtil.doGetJson(url);
			if(!jsonObject.has("errcode")){
				String access_token=jsonObject.getString("access_token");
				Integer expires_in= jsonObject.getInt("expires_in");
				log.debug(access_token);
				log.debug(expires_in.toString());
				gzh gzh = new gzh();
				gzh.setId(3);
				gzh.setAccessToken(access_token);
				gzh.setExpiresIn(expires_in);
				int i = gzhMapper.updateByPrimaryKeySelective(gzh);
				if(i==1){
					return access_token;
				}else {
					return "";
				}
			}



		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}





}






